import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
import "qrc:/qml/components" as Components
import "qrc:/qml/styles" as Styles

/**
 * @brief 仿真车辆面板（重构版）
 * @details 用于SimulatorScreen侧边栏，提供清晰的车辆列表展示和管理功能
 *
 * 主要改进：
 * - 简化顶部工具栏，聚焦核心功能
 * - 优化车辆卡片展示，提升视觉层次
 * - 改进空状态和统计信息展示
 * - 统一操作按钮布局
 */
Rectangle {
    id: root
    color: Styles.Theme.surface

    // ==================== 外部接口 ====================
    property var vehicleListModel: null

    signal vehicleSelected(int agvNumber)
    signal refreshRequested()
    signal resetRequested()
    signal createVehicleRequested()

    // ==================== 内部状态 ====================
    property int selectedAgvNumber: -1
    property int onlineCount: calculateOnlineCount()
    property int busyCount: calculateBusyCount()

    ColumnLayout {
        anchors.fill: parent
        anchors.margins: Styles.Theme.spacingNormal
        spacing: Styles.Theme.spacingNormal

        // ==================== 头部区域 ====================
        ColumnLayout {
            Layout.fillWidth: true
            spacing: Styles.Theme.spacingSmall

            // 标题行
            RowLayout {
                Layout.fillWidth: true
                spacing: Styles.Theme.spacingSmall

                Text {
                    text: qsTr("仿真车辆")
                    color: Styles.Theme.textPrimary
                    font.pixelSize: Styles.Theme.fontSizeLarge
                    font.weight: Font.Bold
                    Layout.fillWidth: true
                }

                // 刷新按钮
                Components.ActionButton {
                    text: "🔄"
                    buttonType: "secondary"
                    size: "small"
                    width: 32
                    height: 32
                    onClicked: refreshRequested()
                    ToolTip.visible: hovered
                    ToolTip.text: qsTr("刷新配置")
                }
            }

            // 统计卡片组
            Rectangle {
                Layout.fillWidth: true
                implicitHeight: statsRow.implicitHeight + Styles.Theme.spacingNormal * 2
                color: Styles.Theme.backgroundAlternate
                radius: Styles.Theme.radiusNormal
                border.color: Styles.Theme.border
                border.width: 1

                RowLayout {
                    id: statsRow
                    anchors.fill: parent
                    anchors.margins: Styles.Theme.spacingNormal
                    spacing: Styles.Theme.spacingSmall

                    // 总数统计
                    ColumnLayout {
                        Layout.fillWidth: true
                        spacing: 2

                        Text {
                            text: vehicleListModel ? vehicleListModel.rowCount() : 0
                            color: Styles.Theme.textPrimary
                            font.pixelSize: 20
                            font.weight: Font.Bold
                            Layout.alignment: Qt.AlignHCenter
                        }

                        Text {
                            text: qsTr("总数")
                            color: Styles.Theme.textSecondary
                            font.pixelSize: Styles.Theme.fontSizeSmall
                            Layout.alignment: Qt.AlignHCenter
                        }
                    }

                    Rectangle {
                        Layout.preferredWidth: 1
                        Layout.fillHeight: true
                        Layout.topMargin: 4
                        Layout.bottomMargin: 4
                        color: Styles.Theme.border
                    }

                    // 在线统计
                    ColumnLayout {
                        Layout.fillWidth: true
                        spacing: 2

                        Text {
                            text: onlineCount
                            color: Styles.Theme.success
                            font.pixelSize: 20
                            font.weight: Font.Bold
                            Layout.alignment: Qt.AlignHCenter
                        }

                        Text {
                            text: qsTr("在线")
                            color: Styles.Theme.textSecondary
                            font.pixelSize: Styles.Theme.fontSizeSmall
                            Layout.alignment: Qt.AlignHCenter
                        }
                    }

                    Rectangle {
                        Layout.preferredWidth: 1
                        Layout.fillHeight: true
                        Layout.topMargin: 4
                        Layout.bottomMargin: 4
                        color: Styles.Theme.border
                    }

                    // 忙碌统计
                    ColumnLayout {
                        Layout.fillWidth: true
                        spacing: 2

                        Text {
                            text: busyCount
                            color: Styles.Theme.info
                            font.pixelSize: 20
                            font.weight: Font.Bold
                            Layout.alignment: Qt.AlignHCenter
                        }

                        Text {
                            text: qsTr("执行中")
                            color: Styles.Theme.textSecondary
                            font.pixelSize: Styles.Theme.fontSizeSmall
                            Layout.alignment: Qt.AlignHCenter
                        }
                    }
                }
            }
        }

        // ==================== 快速操作栏 ====================
        RowLayout {
            Layout.fillWidth: true
            spacing: Styles.Theme.spacingSmall

            Components.ActionButton {
                text: qsTr("车辆管理")
                buttonType: "primary"
                size: "small"
                Layout.fillWidth: true
                onClicked: createVehicleRequested()
            }

            Components.ActionButton {
                text: qsTr("重置全部")
                buttonType: "secondary"
                size: "small"
                Layout.fillWidth: true
                onClicked: resetRequested()
            }
        }

        // ==================== 车辆列表 ====================
        Rectangle {
            Layout.fillWidth: true
            Layout.fillHeight: true
            color: "transparent"
            border.color: Styles.Theme.border
            border.width: 1
            radius: Styles.Theme.radiusNormal

            ScrollView {
                anchors.fill: parent
                anchors.margins: 1
                clip: true
                ScrollBar.horizontal.policy: ScrollBar.AlwaysOff

                ListView {
                    id: vehicleListView
                    model: vehicleListModel
                    spacing: Styles.Theme.spacingSmall
                    topMargin: Styles.Theme.spacingSmall
                    bottomMargin: Styles.Theme.spacingSmall
                    leftMargin: Styles.Theme.spacingSmall
                    rightMargin: Styles.Theme.spacingSmall

                    delegate: Rectangle {
                        width: vehicleListView.width - Styles.Theme.spacingNormal
                        implicitHeight: cardContent.implicitHeight + Styles.Theme.spacingNormal * 2
                        radius: Styles.Theme.radiusNormal
                        color: selectedAgvNumber === model.agvNumber
                               ? Styles.Theme.backgroundSelected
                               : (mouseArea.containsMouse ? Qt.lighter(Styles.Theme.surface, 1.03) : Styles.Theme.surface)
                        border.color: selectedAgvNumber === model.agvNumber
                                      ? Styles.Theme.primary
                                      : (mouseArea.containsMouse ? Styles.Theme.primary : Styles.Theme.border)
                        border.width: selectedAgvNumber === model.agvNumber ? 2 : 1

                        // 左侧状态指示条
                        Rectangle {
                            width: 4
                            height: parent.height - 4
                            anchors.left: parent.left
                            anchors.leftMargin: 2
                            anchors.verticalCenter: parent.verticalCenter
                            radius: 2
                            color: getVehicleStatusColor(model.isOnline, model.isControlled, model.isCharging)
                        }

                        Behavior on color { ColorAnimation { duration: 150 } }
                        Behavior on border.color { ColorAnimation { duration: 150 } }

                        MouseArea {
                            id: mouseArea
                            anchors.fill: parent
                            hoverEnabled: true
                            cursorShape: Qt.PointingHandCursor
                            onClicked: {
                                selectedAgvNumber = model.agvNumber
                                vehicleSelected(model.agvNumber)
                            }
                        }

                        ColumnLayout {
                            id: cardContent
                            anchors.fill: parent
                            anchors.leftMargin: Styles.Theme.spacingNormal + 6
                            anchors.rightMargin: Styles.Theme.spacingNormal
                            anchors.topMargin: Styles.Theme.spacingSmall
                            anchors.bottomMargin: Styles.Theme.spacingSmall
                            spacing: Styles.Theme.spacingXSmall

                            // 第一行：编号 + 名称 + 在线状态
                            RowLayout {
                                Layout.fillWidth: true
                                spacing: Styles.Theme.spacingSmall

                                Text {
                                    text: qsTr("AGV %1").arg(model.agvNumber)
                                    color: Styles.Theme.textPrimary
                                    font.pixelSize: Styles.Theme.fontSizeMedium
                                    font.weight: Font.Bold
                                }

                                Text {
                                    text: model.name || qsTr("未命名")
                                    color: Styles.Theme.textSecondary
                                    font.pixelSize: Styles.Theme.fontSizeSmall
                                    elide: Text.ElideRight
                                    Layout.fillWidth: true
                                }

                                // 在线状态指示器
                                Rectangle {
                                    Layout.preferredWidth: 8
                                    Layout.preferredHeight: 8
                                    radius: 4
                                    color: model.isOnline ? Styles.Theme.success : Styles.Theme.textTertiary
                                }
                            }

                            // 第二行：位置信息
                            RowLayout {
                                Layout.fillWidth: true
                                spacing: 4

                                Text {
                                    text: "📍"
                                    font.pixelSize: 10
                                }

                                Text {
                                    text: model.currentStation || qsTr("位置未知")
                                    color: model.currentStation ? Styles.Theme.textPrimary : Styles.Theme.textTertiary
                                    font.pixelSize: Styles.Theme.fontSizeSmall
                                    Layout.fillWidth: true
                                    elide: Text.ElideRight
                                }

                                // 电池显示
                                Rectangle {
                                    Layout.preferredWidth: 50
                                    Layout.preferredHeight: 20
                                    radius: Styles.Theme.radiusSmall
                                    color: Qt.alpha(getBatteryColor(model.batteryLevel), 0.15)
                                    border.color: getBatteryColor(model.batteryLevel)
                                    border.width: 1

                                    Text {
                                        anchors.centerIn: parent
                                        text: model.batteryLevel + "%"
                                        color: getBatteryColor(model.batteryLevel)
                                        font.pixelSize: Styles.Theme.fontSizeSmall
                                        font.weight: Font.Bold
                                    }
                                }
                            }

                            // 第三行：状态标签
                            RowLayout {
                                Layout.fillWidth: true
                                spacing: 6
                                visible: model.isControlled || model.isCharging

                                Rectangle {
                                    visible: model.isControlled
                                    Layout.preferredWidth: controlledLabel.width + 12
                                    Layout.preferredHeight: 20
                                    radius: 10
                                    color: Qt.alpha(Styles.Theme.info, 0.15)

                                    Text {
                                        id: controlledLabel
                                        anchors.centerIn: parent
                                        text: qsTr("🚚 执行中")
                                        color: Styles.Theme.info
                                        font.pixelSize: 10
                                        font.weight: Font.Medium
                                    }
                                }

                                Rectangle {
                                    visible: model.isCharging
                                    Layout.preferredWidth: chargingLabel.width + 12
                                    Layout.preferredHeight: 20
                                    radius: 10
                                    color: Qt.alpha(Styles.Theme.warning, 0.15)

                                    Text {
                                        id: chargingLabel
                                        anchors.centerIn: parent
                                        text: qsTr("⚡ 充电中")
                                        color: Styles.Theme.warning
                                        font.pixelSize: 10
                                        font.weight: Font.Medium
                                    }
                                }

                                Item { Layout.fillWidth: true }
                            }
                        }
                    }

                    // 空状态展示
                    Item {
                        visible: vehicleListView.count === 0
                        anchors.centerIn: parent
                        width: parent.width
                        height: parent.height

                        ColumnLayout {
                            anchors.centerIn: parent
                            spacing: Styles.Theme.spacingNormal

                            Text {
                                text: "🚛"
                                font.pixelSize: 48
                                Layout.alignment: Qt.AlignHCenter
                                opacity: 0.5
                            }

                            Text {
                                text: qsTr("暂无仿真车辆")
                                color: Styles.Theme.textPrimary
                                font.pixelSize: Styles.Theme.fontSizeMedium
                                font.weight: Font.Bold
                                Layout.alignment: Qt.AlignHCenter
                            }

                            Text {
                                text: qsTr("点击\\\"车辆管理\\\"按钮开始添加")
                                color: Styles.Theme.textSecondary
                                font.pixelSize: Styles.Theme.fontSizeSmall
                                Layout.alignment: Qt.AlignHCenter
                            }

                            Components.ActionButton {
                                text: qsTr("+ 添加车辆")
                                buttonType: "primary"
                                Layout.alignment: Qt.AlignHCenter
                                onClicked: createVehicleRequested()
                            }
                        }
                    }
                }
            }
        }
    }

    // ==================== 辅助函数 ====================
    function getVehicleStatusColor(isOnline, isControlled, isCharging) {
        if (!isOnline) return Styles.Theme.textTertiary
        if (isCharging) return Styles.Theme.warning
        if (isControlled) return Styles.Theme.info
        return Styles.Theme.success
    }

    function getBatteryColor(level) {
        if (level <= 20) return Styles.Theme.danger
        if (level <= 50) return Styles.Theme.warning
        return Styles.Theme.success
    }

    function calculateOnlineCount() {
        if (!vehicleListModel) return 0
        let count = 0
        for (let i = 0; i < vehicleListModel.rowCount(); i++) {
            let data = vehicleListModel.getAgvData(i)
            if (data && data.isOnline) count++
        }
        return count
    }

    function calculateBusyCount() {
        if (!vehicleListModel) return 0
        let count = 0
        for (let i = 0; i < vehicleListModel.rowCount(); i++) {
            let data = vehicleListModel.getAgvData(i)
            if (data && data.isOnline && data.isControlled) count++
        }
        return count
    }

    // ==================== 生命周期 ====================
    Connections {
        target: vehicleListModel
        function onRowsInserted() { updateStats() }
        function onRowsRemoved() { updateStats() }
        function onDataChanged() { updateStats() }
    }

    function updateStats() {
        onlineCount = calculateOnlineCount()
        busyCount = calculateBusyCount()
    }
}
